﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Services;
using Catering.View_Operaction;
using System.Collections;
using Catering_Rules;
using Catering_Model;

namespace Catering.Catering_Page.Caipin.Caipin_jcsz
{
    public partial class sousuoshipu : UserIsNull
    {
        View_Operaction_Common voc = new View_Operaction_Common();
        T_Recipes tRecipes = new T_Recipes();//食谱管理
        T_RecipesWeek tRecipesWeek = new T_RecipesWeek();//食谱周期管理
        T_RecipeInformation tRecipeInformation = new T_RecipeInformation();//食谱菜品详细
        T_RecipeInformationInfo tRecipeInformationInfo = new T_RecipeInformationInfo();//食谱菜品用量详细

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SearchDate.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-MM'})");
                Bind_Data_to_Controls.Bind_Area_ddl(Dr_Operaction, Base_IsAdmin, Base_Groupid, Base_Companyid, true, true);
                Bind_Data_to_Controls.Bind_Class_ddl(Dr_Operaction.SelectedItem, Dr_Class, Base_IsAdmin, Base_Classid, true);
            }
        }

        protected void select_sihpu_click(object sender, EventArgs e)
        {
            this.Repeater1.DataSource = null;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            string strDate = this.SearchDate.Text.Trim();
            DateTime dttime = DateTime.MinValue;
            DateTime.TryParse(strDate, out dttime);

            //区域测试屏蔽
            //sb.Append(" AID=" + LoginPersonnel.AreaID);//区域
            if (this.Dr_Operaction.SelectedValue != "-10" || this.Dr_Class.SelectedValue != "-10")
            {
                sb.Append(Toolss.AddSQLWhere(sb.ToString(), " ( "));

                if (this.Dr_Operaction.SelectedValue != "-10")
                {
                    sb.Append(" AreaID=" + this.Dr_Operaction.SelectedValue);
                    if (this.Dr_Class.SelectedValue != "-10")
                    {
                        sb.Append(" and ClassIDs=" + this.Dr_Class.SelectedValue);
                    }
                }
                else
                {
                    sb.Append(" ClassIDs=" + this.Dr_Class.SelectedValue);
                }

                sb.Append(" or IsBiaoZhun=1 ) ");
            }

            if (dttime > DateTime.MinValue)
            {
                sb.Append(Toolss.AddSQLWhere(sb.ToString(), " year(StateDate)= " + dttime.Year + " and month(StateDate)= " + dttime.Month + " "));
            }

            DataSet ds = new Catering_Rules.T_Recipes().GetList(sb.ToString(),"IsBiaoZhun desc");
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt_shipu = ds.Tables[0];
                this.Repeater1.DataSource = dt_shipu;
            }
            this.Repeater1.DataBind();
        }

        public int GetAVGOld(string strRecipesID)
        {
            Catering_Rules.GroupCatering crgc = new Catering_Rules.GroupCatering();
            Catering_Model.GroupCatering cmgc = crgc.GetModel(Convert.ToInt32(strRecipesID));
            return (cmgc.MOld + cmgc.Wold) / 2;
        }

        protected void Dr_Operaction_SelectedIndexChanged(object sender, EventArgs e)
        {
            Bind_Data_to_Controls.Bind_Class_ddl(Dr_Operaction.SelectedItem, Dr_Class, Base_IsAdmin, Base_Classid, true);
            this.select_sihpu_click(null, null);
        }

        //批量删除食谱
        [WebMethod]
        public static string BatchDel(string RecipesIDS)
        {
            T_Recipes tRecipes=new T_Recipes();

            if (RecipesIDS.Length <= 0)
            {
                return "请选择要删除的食谱！";
            }

            if (new Catering_Rules.T_RecipeInformation().IsExistsExamineByWhere("MID in(" + RecipesIDS + ")"))
            {
                return "要删除的食谱存在已检查记录，无法删除！";
            }

            E_Personnel LoginPersonnel = (E_Personnel)HttpContext.Current.Session["UserInfo"];
            if (LoginPersonnel.id != 1) //若当前用户不是管理员
            {
                DataSet ds = tRecipes.GetNotMyList(RecipesIDS, LoginPersonnel.id);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    return "无法删除他人制作的食谱，请重新选择要删除的食谱！"; 
                }
            }

            for (int i = 0; i < RecipesIDS.Split(',').Length; i++)
            {
                int RecipesID = int.Parse(RecipesIDS.Split(',')[i]);
                new Catering_Rules.T_Recipes().Delete(RecipesID);
                new Catering_Rules.T_RecipesWeek().DeleteListBywhere("RecipesID=" + RecipesID);
                DataTable dt_RecipeInformation = new Catering_Rules.T_RecipeInformation().GetList("MID=" + RecipesID).Tables[0];
                foreach (DataRow row in dt_RecipeInformation.Rows)
                {
                    new Catering_Rules.T_RecipeInformationInfo().DeleteListBywhere("RecipeInformationID=" + row["id"].ToString());
                }
                new Catering_Rules.T_RecipeInformation().DeleteListBywhere("MID=" + RecipesID);
                new Catering_Rules.RecipesRule().DeleteByRecipesID(RecipesID);//删除食谱规则
            }
            return "OK";
        }

        //修改食谱
        [WebMethod]
        public static string Edit_Shipu(string ShipuID, string ShipuName)
        {
            T_Recipes tRecipes = new T_Recipes();
             E_Personnel LoginPersonnel = (E_Personnel)HttpContext.Current.Session["UserInfo"];
            int id = 0;
            Int32.TryParse(ShipuID, out id);
            if (id > 0 && !string.IsNullOrEmpty(ShipuName.Trim()))
            {
                E_Recipes eRecipes = tRecipes.GetModel(id);
                eRecipes.CateringName = ShipuName.Trim();
                eRecipes.EditPersonnelID = LoginPersonnel.id;
                eRecipes.EditTime = DateTime.Now;
                bool b=tRecipes.Update(eRecipes);
                return b ? "OK" : "NO";
            }
            return "NO";
        }

        //修改食谱
        [WebMethod]
        public static string Edit_Shipu_BiaoZhun(string ShipuID, int Flag)
        {
            T_Recipes tRecipes = new T_Recipes();
            E_Personnel LoginPersonnel = (E_Personnel)HttpContext.Current.Session["UserInfo"];
            int id = 0;
            Int32.TryParse(ShipuID, out id);
            if (id > 0)
            {
                E_Recipes eRecipes = tRecipes.GetModel(id);
                eRecipes.IsBiaoZhun = (Flag == 1);
                eRecipes.EditPersonnelID = LoginPersonnel.id;
                eRecipes.EditTime = DateTime.Now;
                bool b = tRecipes.Update(eRecipes);
                return b ? "OK" : "NO";
            }
            return "NO";
        }

        //复制食谱
        [WebMethod]
        public static ArrayList Clone_Shipu(string StrShipuID, string StrClassID)
        {
            ArrayList al = new ArrayList();
            al.Add("NO");
            int cid = 0;
            int classid = 0;
            Int32.TryParse(StrShipuID, out cid);
            Int32.TryParse(StrClassID, out classid);
            classid = int.Parse(HttpContext.Current.Session["ClassID"].ToString()); //复制的食谱应该按照当前操作人的班主为准
            Catering_Model.ClassInfo md_cl = new Catering_Rules.ClassInfo().GetModel(classid);
            Catering_Model.E_Recipes md_re = new Catering_Rules.T_Recipes().GetModel(cid);
            if (md_re != null)
            {
                Catering_Model.GroupCatering md_gc = new Catering_Rules.GroupCatering().GetModel(md_re.GroupID);
                if (md_gc != null)
                {
                    //配餐群体表
                    int maxid = new Catering_Rules.GroupCatering().GetMaxId();
                    md_gc.id = maxid;
                    md_gc.ClaassID = classid;
                    md_gc.AreaID = md_cl.AreaID;
                    new Catering_Rules.GroupCatering().Add(md_gc);

                    //配餐群体详细表
                    DataTable dt = new Catering_Rules.CateringGroupInfo().GetList(" GroupID=" + md_re.GroupID).Tables[0];
                    if (dt != null)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            Catering_Model.CateringGroupInfo md_cgi = new Catering_Model.CateringGroupInfo();
                            md_cgi.SexID = Convert.ToInt32(dt.Rows[i]["SexID"]);
                            md_cgi.OldAreaID = Convert.ToInt32(dt.Rows[i]["OldAreaID"]);
                            md_cgi.LaborGradeID = Convert.ToInt32(dt.Rows[i]["LaborGradeID"]);
                            md_cgi.Group_tedianID = Convert.ToInt32(dt.Rows[i]["Group_tedianID"]);
                            md_cgi.Number = Convert.ToInt32(dt.Rows[i]["Number"]);
                            md_cgi.GroupID = maxid;
                            md_cgi.id = new Catering_Rules.CateringGroupInfo().GetMaxId();
                            new Catering_Rules.CateringGroupInfo().Add(md_cgi);
                        }
                        dt.Dispose();
                    }

                    //食谱表
                    DateTime MaxDate = new Catering_Rules.T_Recipes().GetRecipesMaxDateTime(md_gc.ClaassID);//副本起始时间
                    Catering_Model.E_Recipes md_rp = new Catering_Model.E_Recipes();
                    md_rp.CateringName = md_gc.GCName;
                    md_rp.ClassID = md_gc.ClaassID;
                    md_rp.GroupID = md_gc.id;
                    md_rp.PID = 0;//表明为群体配餐
                    md_rp.Number = new Catering_Rules.CateringGroupInfo().GetSumRSByGroupID(maxid.ToString());
                    md_rp.AreaID = md_gc.AreaID;
                    md_rp.ClassIDs = md_gc.ClaassID;
                    md_rp.StateDate = new DateTime(MaxDate.Year, MaxDate.Month, MaxDate.Day);
                    md_rp.StopDate = md_rp.StateDate; //暂时与起始时间保持一致
                    md_rp.EditPersonnelID = int.Parse(HttpContext.Current.Session["UserID"].ToString());
                    md_rp.EditTime = DateTime.Now;
                    new Catering_Rules.T_Recipes().Add(md_rp);

                    //食谱周期表
                    List<Catering_Model.E_RecipesWeek> list = new Catering_Rules.T_RecipesWeek().GetModelList(" RecipesID=" + cid + " ORDER BY startDate ASC ");
                    int datetype = 0;//7天制
                    if (list != null && list.Count() > 0)
                    {
                        foreach (Catering_Model.E_RecipesWeek item in list)
                        {
                            if (datetype == 0) datetype = (item.endDate - item.startDate).Days;
                            item.startDate = MaxDate;
                            item.endDate = MaxDate.AddDays(datetype);
                            item.RecipesID = md_rp.id;
                            new Catering_Rules.T_RecipesWeek().Add(item);
                            MaxDate = GetStartDate(item.endDate);
                        }
                    }
                    md_rp.StopDate = MaxDate.AddDays(-1); //更具时间周期修正结束时间
                    new Catering_Rules.T_Recipes().Update(md_rp);


                    /* 该复制逻辑存在周期对应问题 因此屏蔽
                    //食谱详细表
                    List<Catering_Model.E_RecipeInformation> li_ri = new Catering_Rules.T_RecipeInformation().GetModelList(" MID=" + cid);
                    if (li_ri != null && li_ri.Count() > 0)
                    {
                        foreach (Catering_Model.E_RecipeInformation item in li_ri)
                        {
                            Catering_Model.E_RecipesWeek rw = new Catering_Rules.T_RecipesWeek().GetModel(" RecipesID=" + md_rp.id + " and Number=" + item.temp1);
                            int old_rei_id = item.id;
                            item.MID = md_rp.id;
                            item.Date = rw.startDate.AddDays((item.Week == 0 ? 7 : item.Week) - 1);
                            //item.id = new Catering_Rules.T_RecipeInformation().GetMaxId();
                            new Catering_Rules.T_RecipeInformation().Add(item);
                            //食谱详细原料表
                            List<Catering_Model.E_RecipeInformationInfo> li_rifo = new Catering_Rules.T_RecipeInformationInfo().GetModelList(" RecipeInformationID=" + old_rei_id);
                            foreach (Catering_Model.E_RecipeInformationInfo item_ifo in li_rifo)
                            {
                                ////检查原料的配送区域
                                Catering_Model.ClassInfo md_class = new Catering_Rules.ClassInfo().GetModel(md_rp.ClassIDs);
                                if (md_class.AID <= 0 && md_class.id != 50) continue;
                                string checkwhere = " RAWID=" + item_ifo.RawID + " AND InDBID LIKE '" + md_class.AID + "%'";
                                DataTable dt_ck = new Catering_Rules.RawMaterial_Area().GetList(checkwhere).Tables[0];
                                if (dt_ck.Rows.Count == 0) continue;

                                item_ifo.RecipeInformationID = item.id;
                                new Catering_Rules.T_RecipeInformationInfo().Add(item_ifo);
                            }
                        }
                    }
                    */

                    al.Clear();
                    al.Add("OK");
                    al.Add(md_rp.id);
                    al.Add(classid);
                    return al;
                }
            }
            return al;
        }

        public string GetBiaoZhunStr(string strid, string isbz, string strclassid)
        {
            if (LoginPersonnel.ClassID.ToString() == strclassid || Base_IsAdmin)
            {
                return "<a href=\"javascript:Tr_Edit_BiaoZhun('" + strid + "'," + (isbz == "True" ? '0' : '1') + ")\" title='点击修改标准食谱'>" + (isbz == "True" ? "<span class='Red'>是</span>" : "否") + "</a>";
            }
            else
            {
                return isbz == "True" ? "<span class='Red'>是</span>" : "否";
            }
        }

        public string EditCateringName(string strid, string name, string strclassid)
        {
            if (LoginPersonnel.ClassID.ToString() == strclassid)
            {
                return "<a href='javascript:void(0);'><img src='../../../Images/file.gif' alt='编辑食谱名称' onclick=\"Tr_Edit('" + strid + "','" + (name == "" ? "&nbsp;" : name) + "')\" /></a>";
            }
            else
            {
                return "&nbsp;";
            }
        }

        public string GetStrCloneRecipes(string strid)
        {
            int id = 0;
            Int32.TryParse(strid, out id);
            if (id > 0)
            {
                Catering_Model.E_Recipes md_re = new Catering_Rules.T_Recipes().GetModel(id);
                if (md_re.PID == 0)
                {
                    return "<a href='javascript:void(0);' onclick=\"ShipuClone('" + strid + "')\">复制食谱</a>";
                }
            }
            return "";
        }

        public static DateTime GetStartDate(DateTime dtime)
        {
            DateTime date = DateTime.Now;
            date = dtime.AddDays(1);
            switch (date.DayOfWeek.ToString())
            {
                case "Monday": return date;
                case "Tuesday": return date.AddDays(6);
                case "Wednesday": return date.AddDays(5);
                case "Thursday": return date.AddDays(4);
                case "Friday": return date.AddDays(3);
                case "Saturday": return date.AddDays(2);
                default: return date.AddDays(1);
            }
        }

        //列表事件
        protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                int RecipesID = int.Parse(e.CommandArgument.ToString());
                if (tRecipeInformation.IsExistsExamineByWhere("MID=" + RecipesID))
                { 
                    ClientScript.RegisterClientScriptBlock(Page.GetType(),"alert","<script>alert('该食谱已检查，无法删除！');</script>");
                    return;
                }
                tRecipes.Delete(RecipesID);
                tRecipesWeek.DeleteListBywhere("RecipesID=" + RecipesID);
                DataTable dt_RecipeInformation = tRecipeInformation.GetList("MID=" + RecipesID).Tables[0];
                foreach (DataRow row in dt_RecipeInformation.Rows)
                {
                    tRecipeInformationInfo.DeleteListBywhere("RecipeInformationID=" + row["id"].ToString());
                }
                tRecipeInformation.DeleteListBywhere("MID=" + RecipesID);
                new Catering_Rules.RecipesRule().DeleteByRecipesID(RecipesID);//删除食谱规则
                this.select_sihpu_click(null, null);
            }
        }

        //按钮权限控制
        protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                ImageButton BtnDel = e.Item.FindControl("BtnDel") as ImageButton;//找到里层的Del按钮
                DataRowView Row = (DataRowView)e.Item.DataItem;//找到分类Repeater关联的数据项 
                bool IsExistsExamine = new Catering_Rules.T_RecipeInformation().IsExistsExamineByWhere("MID in(" + Row["id"].ToString() + ")");
                bool BtnDelIsShow = (LoginPersonnel.ClassID.ToString() == Row["ClassID"].ToString() || LoginPersonnel.id == 1) && !IsExistsExamine; //判断该食谱是否为本班组 或 当前用户为管理员
                BtnDel.Visible = BtnDelIsShow;
            }
        }
    }
}